import os
from django.core.management.base import NoArgsCommand
from django.contrib.gis.gdal import *
from django.contrib.gis.utils import LayerMapping
from django.conf import settings
from django.template.defaultfilters import slugify
from chicago.models import *

DATA_DIR = os.path.abspath(os.path.join(settings.PROJECT_DIR,'data','chicago'))

verbose = True
encoding='iso-8859-1'

class Command(NoArgsCommand):

    help = 'Import the shp files into the database using the Django models.'

    def handle_noargs(self, **options):

        senate_mapping = {
            'perimeter' : 'PERIMETER',
            'senate' : 'SENATE_',
            'senate_id' : 'SENATE_ID',
            'name' : 'NAME',
            'party' : 'PARTY',
            'telephone' : 'TELEPHONE',
            'district' : 'DISTRICT',
            'area' : 'MULTIPOLYGON',
            'shape_area' : 'SHAPE_AREA',
            'shape_length' : 'SHAPE_LEN',
        }

        senate_shp = os.path.abspath(
                        os.path.join(DATA_DIR, 'IL_Senate2000.shp'))

        ilhouse_mapping = {
            'perimeter' : 'PERIMETER',
            'new_ilhouse' : 'NEW_ILHOUS',
            'new_ilhouse1' : 'NEW_ILHO_1',
            'name' : 'NAME',
            'party' : 'PARTY',
            'telephone' : 'TELEPHONE',
            'district' : 'DISTRICT',
            'area' : 'POLYGON',
            'shape_area' : 'SHAPE_AREA',
            'shape_length' : 'SHAPE_LEN',
        }

        ilhouse_shp = os.path.abspath(
                        os.path.join(DATA_DIR,'IL_House2000.shp'))

        wards_mapping = {
            'perimeter' : 'PERIMETER',
            'ward' : 'WARD', 
            'alderman' : 'ALDERMAN',
            'ward_phone' : 'WARD_PHONE', 
            'hall_phone' : 'HALL_PHONE', 
            'office_address' : 'HALL_OFFIC', 
            'address' : 'ADDRESS', 
            'poly' : 'POLYGON',
            'shape_area' : 'SHAPE_AREA',
            'shape_length' : 'SHAPE_LEN',
        }

        wards_shp = os.path.abspath(
                        os.path.join(DATA_DIR,'wards.shp'))

#Ignoring TIFS for now
#tifs_mapping = {
#    'name':'NAME',
#    'name_trim':'NAME_TRIM', 
#    'ref':'REF', 
#    'ind':'IND', 
#    'type':'TYPE', 
#    'use':'USE', 
#    'show':'SHOW', 
#    'area':'POLYGON',
#}
#
#tifs_shp = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data/tifs.shp'))
#

        congress_mapping = {
            'uscong':'NEW_USCONG',
            'name':'NAME', 
            'district':'DISTRICT', 
            'area':'POLYGON',
        }
        congress_shp = os.path.abspath(
                        os.path.join(DATA_DIR, 'US_Congress.shp'))

        lm = LayerMapping(Senate, senate_shp, senate_mapping,
                          transform=False, encoding='iso-8859-1')
        lm.save(strict=True, verbose=verbose)

        lm = LayerMapping(House, ilhouse_shp, ilhouse_mapping,
                          transform=False, encoding='iso-8859-1')
        lm.save(strict=True, verbose=verbose)

        lm = LayerMapping(Congress, congress_shp, congress_mapping,
                          transform=False, encoding='iso-8859-1')
        lm.save(strict=True, verbose=verbose)

        #lm = LayerMapping(Ward, wards_shp, wards_mapping,
        #                  transform=False, encoding='iso-8859-1')
        #lm.save(strict=True, verbose=verbose)

        # Wards need a bit more massaging
        ds = DataSource(wards_shp)
        lyr = ds[0]
        for l in lyr:
            w = Ward(
                    perimeter = l.get('PERIMETER'),
                    ward = l.get('WARD'), 
                    alderman = unicode(l.get('ALDERMAN'), encoding),
                    ward_phone = unicode(l.get('WARD_PHONE'), encoding),
                    hall_phone = l.get('HALL_PHONE'), 
                    office_address = l.get('HALL_OFFIC'), 
                    address = l.get('ADDRESS'), 
                    area = l.geom.wkt,
                    shape_area = l.get('SHAPE_AREA'),
                    shape_length = l.get('SHAPE_LEN'),
                )
            try:
                w.save()
                print 'saved %s' % w
            except ValueError:
                w.ward = 0
                w.save()
                print 'saved %s with ward = 0' % w

        # Finally loop through all the objects and create
        # foreign key for reps.

        model_name_map = ( (Ward,'alderman'),
                           (Senate, 'name'),
                           (House, 'name'),
                           (Congress, 'name'))

        print 'updating Rep foreign keys'
        for m in model_name_map:
            model = m[0]
            attr = m[1]

            for obj in model.objects.all():
                name_attr = getattr(obj, attr)
                f = m = l = s = ''
                try:
                   f,m,l = name_attr.split(' ')
                except:
                    try:
                        f,l = name_attr.split(' ')
                    except ValueError:
                         try:
                            f,m,l,s = name_attr.split(' ')
                            l = "%s %s" % (l,s)
                         except:
                            print 'skipped ', obj, attr
                            continue
                r = Rep(
                        first_name = f.title(),
                        last_name = l.title(),
                        middle_name = m.title(),
                        slug = slugify(name_attr)
                    )
                # Save the Rep
                r.save()
                # Update the region object
                obj.rep = r
                obj.save()
